<?php
namespace Common\Behaviors;
class wxLoginBehavior extends \Think\Behavior {
	//行为执行入口
	public function run(&$param) {
		$this->user_id = session("user_id");
		$user_info = BoxModel("system_member")->where(array('user_id' => $this->user_id))->find();
		if ($user_info['user_id']) {
			//已经登录
			return true;
		}

		if (checkAgent()) {
			//非微信浏览器
			return true;
		}
		$this->LoginUrl();
		//$this->store_id=getStoreID();
		$this->store_id = I('store_id', "1", "intval");
		$this->storeInfo = BoxModel("addon_wx_config")->load($this->store_id);
		$param = array(
			'token' => $this->storeInfo['token'],
			'appID' => $this->storeInfo['appID'],
			'appsecret' => $this->storeInfo['appsecret'],
		);
		$this->wechatObj = new \Common\Org\weiXin($param);
		$code = I('code');
		if ($code) {
			$this->OAuthLogin($code);
		} else {
			$this->getCode();
		}

	}
	protected function LoginUrl() {
		$backUl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$backUl = urlencode($backUl);
		if ($_SERVER['HTTP_HOST'] != str_replace("http://", "", LoginUrl)) {
			echo '<script language="javascript">window.location.href="' . LoginUrl . "/Login/index?backUrl=" . $backUl . '"</script>';
			exit();
			//$this->redirect(LoginUrl . "?backUrl=" . $backUl);
		}
		//dump($_SERVER['HTTP_HOST']);exit();
	}

	protected function getCode() {
		$this->appID = $this->storeInfo['appID'];
		$scope = I('scope', "snsapi_base");
		$backUl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		/********登录成功之后跳转******/
		$bool = strpos($backUl, "?");
		$backUl = $bool === false ? ($backUl . "?backUrl=" . I('backUrl')) : ($backUl . "&backUrl=" . I('backUrl'));
		$backUl = urlencode($backUl);
		//$backUl=I('backUrl',$backUl); //登录之后回调地址
		/*******如果在微信中浏览直接使用微信同步登录*********/
		$scope = $scope ? $scope : "snsapi_base";
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appID}&redirect_uri={$backUl}&response_type=code&scope={$scope}&state=123#wechat_redirect";
		header("location:$url");
	}

	/*******微信自动登录,授权后返回Code登录*******/
	protected function OAuthLogin($code) {
		$data = $this->wechatObj->OAuthUserInfo($code);
		if (!($openid = $data['openid'])) {
			$this->jumpToUrl();
		}
		//网页授权登录
		if ($data['scope'] == "snsapi_userinfo") {
			$user_info = $this->wechatObj->UserInfoBySnsapi($openid, $data['access_token']);
		} else {
			$user_info = $this->wechatObj->UserInfo($openid);
		}

		$where = array(
			'type_uid' => $user_info['openid'],
			'type' => 'weixin',
		);
		$sync_login = BoxModel("system_member")->where(array('openid' => $user_info['openid']))->find();
		if ($user_id = $sync_login['user_id']) {
			Logic("BoxSns", "Member")->saveLogin($user_id);
		} elseif (is_array($user_info)) {
			$user_id = Logic("BoxSns", "Member")->WxCreateMember($user_info);
			Logic("BoxSns", "Member")->saveLogin($user_id);
		}
		/******单点登录****/
		$user_info = BoxModel("SystemMember")->where(array('user_id' => $user_id))->find();
		$r = Logic("BoxSns", "Member")->do_login($user_info['user_name'], $user_info['password'], 1);
		$this->jumpToUrl();
	}

	/*********微信登录成功，或失败****/
	function jumpToUrl() {
		$backUl = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
		$backUl = preg_replace('/(&|\?)code=[^&]+/', '', $backUl);
		header("location:$backUl");
		exit();
	}
}
